import { ILayerItem } from '@renderer/types/layerType'
import { generateUUID } from '@renderer/utils/utils'
import { defineStore } from 'pinia'

export const useLayerStore = defineStore('layer', {
  state: () => ({
    layers: [] as ILayerItem[],
    //锁定的节点
    lockNodeIds: [] as string[],
    //当前选择的节点ids
    currentSelectNodeIds: [] as string[],
    //树形结构ref
    treeRef: null as any
  }),

  actions: {
    canvasAddLayer(nodes: any[]) {
      console.log(nodes)
      nodes.forEach((node: any) => {
        this.layers.unshift({
          id: node.id,
          name: node.name,
          zIndex: node.zIndex,
          lock: false,
          type: 'leaf'
        })
      })
    },

    // 获取所有 leaf 类型节点的 id
    getLeafNodeIds(ids: string[]): string[] {
      const result: string[] = []

      for (const id of ids) {
        const item = this.findNodeById(this.layers, id)
        if (item) {
          if (item.type === 'leaf') {
            result.push(item.id)
          } else if (item.type === 'branch') {
            const childIds = item.children?.map((el) => el.id) || []
            const leafIds = this.getLeafNodeIds(childIds)
            result.push(...leafIds)
          }
        } else {
          result.concat([])
        }
      }

      return result
    },

    //选择节点，单个或多个
    selectNodes(ids: string[]) {
      this.currentSelectNodeIds = ids
      const leafIds = this.getLeafNodeIds(ids)
      window.api.handleCanvasData('selectNodesOrEdges', 'resourceMana', true, [leafIds])
    },

    //主进程选择节点
    selectNodesByMain(result: string[]) {
      let ids = [] as string[]
      ids = result.filter((id: string) => !this.lockNodeIds.includes(id))
      this.currentSelectNodeIds = ids
    },

    //切换锁的状态
    toggleLock(id: string) {
      // 找到选中的节点
      const item = this.findNodeById(this.layers, id)
      if (item) {
        item.lock = !item.lock
        const currentLockNodeIds = [] as string[]
        currentLockNodeIds.push(item.id)
        if (item.type === 'branch') {
          const getAllIds = (node: ILayerItem) => {
            node.lock = item.lock
            if (node.type === 'leaf') {
              currentLockNodeIds.push(node.id)
            } else {
              node?.children?.forEach((child: ILayerItem) => {
                getAllIds(child)
              })
            }
          }
          getAllIds(item)
        }

        if (item.lock) {
          this.lockNodeIds = [...this.lockNodeIds, ...currentLockNodeIds]
        } else {
          this.lockNodeIds = this.lockNodeIds.filter(
            (id: string) => !currentLockNodeIds.includes(id)
          )
        }
      }
    },

    // 查找所有选中节点信息（含 parent 和 index）
    getSelectedNodeInfos(
      layers: ILayerItem[],
      selectedIds: string[]
    ): { node: ILayerItem; parent: ILayerItem | null; index: number }[] {
      const selected: { node: ILayerItem; parent: ILayerItem | null; index: number }[] = []

      const find = (nodes: ILayerItem[], parent: ILayerItem | null): boolean => {
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i]

          if (selectedIds.includes(node.id)) {
            selected.push({ node, parent, index: i })
            if (selected.length === selectedIds.length) return true
          }

          if (node.children && find(node.children, node)) {
            return true
          }
        }
        return false
      }

      find(layers, null)
      return selected
    },

    // 获取首个选中节点的信息（用于插入位置）
    getFirstSelectedNodeInfo(
      nodeInfos: { node: ILayerItem; parent: ILayerItem | null; index: number }[],
      firstSelectedId: string
    ) {
      return nodeInfos.find((info) => info.node.id === firstSelectedId)!
    },
    // 创建新编组对象
    createNewGroup(zIndex: number): ILayerItem {
      return {
        id: generateUUID(),
        name: '自定义编组',
        lock: false,
        type: 'branch',
        zIndex,
        children: []
      }
    },
    // 将节点移入编组中（注意逆序）
    moveNodesToGroup(
      nodes: { node: ILayerItem; parent: ILayerItem | null; index: number }[],
      group: ILayerItem
    ) {
      ;[...nodes]
        .sort((a, b) => b.index - a.index)
        .forEach((info) => {
          const sourceList = info.parent ? info.parent.children! : this.layers
          sourceList.splice(info.index, 1)
          group.children!.unshift(info.node)
        })
    },
    // 将新编组插入正确位置
    insertGroupAtTargetPosition(
      group: ILayerItem,
      targetInfo: { parent: ILayerItem | null; index: number }
    ) {
      if (targetInfo.parent) {
        if (!targetInfo.parent.children) targetInfo.parent.children = []
        targetInfo.parent.children.splice(targetInfo.index, 0, group)
      } else {
        this.layers.splice(targetInfo.index, 0, group)
      }
    },
    createGroup() {
      if (this.currentSelectNodeIds.length === 0) return

      const selectedNodeInfos = this.getSelectedNodeInfos(this.layers, this.currentSelectNodeIds)
      if (selectedNodeInfos.length === 0) return

      const firstSelectedInfo = this.getFirstSelectedNodeInfo(
        selectedNodeInfos,
        this.currentSelectNodeIds[0]
      )

      const newGroup = this.createNewGroup(firstSelectedInfo.node.zIndex)

      this.moveNodesToGroup(selectedNodeInfos, newGroup)

      this.insertGroupAtTargetPosition(newGroup, firstSelectedInfo)
    },
    // 查找节点 by id
    findNodeById(nodes: ILayerItem[], id: string): ILayerItem | null {
      for (const node of nodes) {
        if (node.id === id) return node
        if (node.children) {
          const foundNode = this.findNodeById(node.children, id)
          if (foundNode) return foundNode
        }
      }
      return null
    },
    // 查找父节点
    findParentNode(nodes: ILayerItem[], childId: string): ILayerItem | null {
      for (const node of nodes) {
        if (node.children && node.children.some((child) => child.id === childId)) {
          return node
        }
        if (node.children) {
          const parent = this.findParentNode(node.children, childId)
          if (parent) return parent
        }
      }
      return null
    },
    // 取消编组
    ungroup() {
      if (this.currentSelectNodeIds.length !== 1) return
      const selectedNodeId = this.currentSelectNodeIds[0]

      // 找到选中的节点
      const selectedNode = this.findNodeById(this.layers, selectedNodeId)
      if (!selectedNode || selectedNode.type !== 'branch') return // 确保是 branch 类型的节点

      // 查找父节点及其索引位置
      const parent = this.findParentNode(this.layers, selectedNodeId)
      const nodeIndex = parent
        ? parent.children!.indexOf(selectedNode)
        : this.layers.indexOf(selectedNode)

      if (parent) {
        // 如果有父节点，将子节点提升到父节点的同一层级
        parent.children = parent.children!.filter((child) => child.id !== selectedNodeId)
        parent.children!.splice(nodeIndex, 0, ...selectedNode.children!) // 在原位置插入子节点
      } else {
        // 如果没有父节点，说明是根节点，直接操作根层级
        //删除index索引元素
        this.layers.splice(nodeIndex, 1)
        this.layers.splice(nodeIndex, 0, ...selectedNode.children!) // 在原位置插入子节点
      }

      // 删除该编组节点的子节点
      selectedNode.children = [] // 清空子节点
    },

    //编组拖拽排序
    moveNode(data: any) {
      const { sourceId, targetId } = data
      if (sourceId === targetId) return

      const sourceNode = this.findNodeById(this.layers, sourceId)
      const sourceParent = this.findParentNode(this.layers, sourceId)

      const targetNode = this.findNodeById(this.layers, targetId)
      const targetParent = this.findParentNode(this.layers, targetId)

      const sourceIndex = sourceParent
        ? sourceParent.children!.indexOf(sourceNode!)
        : this.layers.indexOf(sourceNode!)

      if (sourceIndex !== -1) {
        if (sourceParent) {
          sourceParent.children!.splice(sourceIndex, 1)
        } else {
          this.layers.splice(sourceIndex, 1)
        }
      }

      const targetIndex = targetParent
        ? targetParent.children!.indexOf(targetNode!)
        : this.layers.indexOf(targetNode!)
      if (targetIndex !== -1) {
        if (targetParent) {
          targetParent.children!.splice(targetIndex, 0, sourceNode!)
        } else {
          this.layers.splice(targetIndex, 0, sourceNode!)
        }
      }

      this.updateZIndex(sourceId, targetId)
    },

    //删除节点
    deleteNode(data?: any[]) {
      const delHandle = (id: string) => {
        const parent = this.findParentNode(this.layers, id)

        const index =
          parent?.children?.findIndex((item) => item.id === id) ??
          this.layers.findIndex((item) => item.id === id)

        if (index !== -1) {
          if (parent) {
            parent.children?.splice(index, 1)
          } else {
            this.layers.splice(index, 1)
          }
        }
      }
      this.currentSelectNodeIds.forEach((id) => {
        delHandle(id)
      })

      if (data) {
        const ids = data.map((item) => item.id)
        ids.forEach((id) => {
          delHandle(id)
        })
      }
    },

    updateNodeText(data: { id: string; text: string }) {
      const nodes = window.api.handleCanvasData('getNodes', 'resourceMana', false, ['id', data.id])
      if (!nodes || nodes.length === 0) {
        this.mainUpdateNameToLayer({ id: data.id, name: data.text })
        return
      }
      const node = nodes[0]
      node.name = data.text
      window.api.handleCanvasData('updateNodes', 'property', true, [node])
    },

    mainUpdateNameToLayer(data: { id: string; name: string }) {
      const result = this.findNodeById(this.layers, data.id)
      if (result) {
        result.name = data.name
      }
    },

    //更改画布里面节点的zIndex
    updateZIndex(sourceId: string, targetId: string) {
      const sourceLeftNodes = this.getLeafNodeIds([sourceId])
      const targetLeftNodes = this.getLeafNodeIds([targetId])

      const targetNodes = [] as any[]
      targetLeftNodes.forEach((id) => {
        const nodes = window.api.handleCanvasData('getNodes', 'resourceMana', false, ['id', id])
        if (nodes && nodes.length > 0) {
          targetNodes.push(nodes[0])
        }

        const edges = window.api.handleCanvasData('getEdges', 'resourceMana', false, ['id', id])
        if (edges && edges.length > 0) {
          targetNodes.push(edges[0])
        }
      })

      //找到targetNodes里面zIndex最大的值
      const maxZIndex = Math.max(...targetNodes.map((node) => node.zIndex))

      const sourceNodes = [] as any[]
      sourceLeftNodes.forEach((id) => {
        const nodes = window.api.handleCanvasData('getNodes', 'resourceMana', false, ['id', id])
        if (nodes && nodes.length > 0) {
          sourceNodes.push(nodes[0])
        }

        const edges = window.api.handleCanvasData('getEdges', 'resourceMana', false, ['id', id])
        if (edges && edges.length > 0) {
          sourceNodes.push(edges[0])
        }
      })
      sourceNodes.forEach((node) => {
        node.zIndex = maxZIndex
      })
      window.api.handleCanvasData('updateNodes', 'resourceMana', true, [sourceNodes])
      window.api.handleCanvasData('updateEdges', 'resourceMana', true, [sourceNodes])
    },

    //清空数据
    clear() {
      this.layers.splice(0, this.layers.length)
    }
  }
})
